package com.banciyuan.bcywebview.biz.zanlist;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.TimelineApi;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.biz.zanlist.decoration.ZanItemOffsetDecoration;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.Timeline;

/**
 * Created by hy on 2015/4/28.
 */
public class RecommendListFragment extends BaseLazyContainerFragment {

    private PullToRefreashRecycleView mRefreshRv;
    private RecyclerView mContentRv;
    private RequestQueue mQueue;
    private ProgressbarHelper mProgressbarHelper;
    private boolean loading = false;
    private boolean hasMore = true;
    private String uid;
    private String since = "0";
    private List<Timeline> gridTimelines = new ArrayList<>();
    private RecommendListAdapter mRecommendAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.zanlist_layout, container, false);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
        Bundle bundle = getArguments();
        uid = bundle.getString(gotoUtil.INTENT_VALUE_ONE);
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarHelper = new ProgressbarHelper(rootview);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                hasMore = true;
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        mRefreshRv = (PullToRefreashRecycleView) rootview.findViewById(R.id.recleview);
        mContentRv = mRefreshRv.getRefreshableView();

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        mContentRv.addItemDecoration(new ZanItemOffsetDecoration(UIUtils.dip2px(4, getActivity())));
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return position == 0 ? 3 : 1;
            }
        });
        mContentRv.setLayoutManager(gridLayoutManager);
    }

    @Override
    protected void initAction() {

        mContentRv.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!loading && hasMore) {
                    loading = true;
                    initData();
                }
            }
        });

        mRefreshRv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                if (!loading) {
                    loading = true;
                    hasMore = true;
                    since = "0";
                    initData();
                }
            }
        });
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + TimelineApi.getUserGrid();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.UID, uid));
        pairs.add(new BcyPair(HttpUtils.UPPULL_SINCE, since));
        pairs.add(new BcyPair(HttpUtils.TAG_FILTER, "tuijian"));
        pairs.add(new BcyPair(HttpUtils.UPPULL_SOURCE, "all"));
        HashMap<String, String> params = HttpUtils.getData(pairs);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        List<Timeline> templist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA),
                                new TypeToken<List<Timeline>>() {
                                }.getType());

                        renderGridTimeline(templist);
                    } catch (Exception e) {
                        onError();
                    }
                } else {
                    onError();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onError();
            }
        };
        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSuccess, url, getActivity(), params);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, params, onSuccess, onErrorProxy);
        mQueue.add(requestParam);
    }

    private void onError() {
        mRefreshRv.onRefreshComplete();
        mProgressbarHelper.onFailed();
        loading = false;
    }

    private void renderGridTimeline(List<Timeline> tempList) {
        String lastTlId = processGridTimelineTempLastId(tempList);
        TimelineFactory.popIllegalItem(tempList);
        if ("0".equals(since)) {
            gridTimelines.clear();
        }
        int start = gridTimelines.size();
        gridTimelines.addAll(tempList);
        if (mRecommendAdapter == null) {
            mRecommendAdapter = new RecommendListAdapter(getActivity(), gridTimelines);
            mContentRv.setAdapter(mRecommendAdapter);
        } else {
            if ("0".equals(since)) {
                mRecommendAdapter.notifyDataSetChanged();
            } else {
                mRecommendAdapter.notifyItemRangeInserted(start + 1, gridTimelines.size() - start);
            }
        }
        onSucces(tempList, lastTlId);
    }

    private void onSucces(List<Timeline> tempList, String lastTlId) {
        if (tempList.isEmpty()) {
            hasMore = false;
        }
        since = lastTlId;
        loading = false;
        mProgressbarHelper.onSuccess();
        mRefreshRv.onRefreshComplete();
    }

    private String processGridTimelineTempLastId(List<Timeline> tempList) {
        String lastTlId;
        if (!tempList.isEmpty()) {
            hasMore = true;
            lastTlId = tempList.get(tempList.size() - 1).getTl_id();
        } else {
            lastTlId = "0";
            hasMore = false;
        }
        return lastTlId;
    }
}
